﻿using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

public class UICanvasMgr : Singleton<UICanvasMgr>
{
    private GameObject _rootCanvas;
    private Dictionary<CanvasSortingOrderEnum,GameObject> _canvasDic
        = new Dictionary<CanvasSortingOrderEnum, GameObject>();

    public override void Init()
    {
        base.Init();
        foreach (CanvasSortingOrderEnum type in Enum.GetValues(typeof(CanvasSortingOrderEnum)))
        {
            GameObject orderCanvas = new GameObject(string.Format("Canvas({0})", type.ToString()));
            UIHelper.Instance.AddChild(RootCanvas, orderCanvas);
            Canvas canvas = orderCanvas.AddComponent<Canvas>();
            canvas.overrideSorting = true;
            canvas.sortingOrder = (int)type;

            RectTransform canvasRect = orderCanvas.GetComponent<RectTransform>();
            canvasRect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, 0);
            canvasRect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, 0);
            canvasRect.anchorMax = Vector2.one;
            canvasRect.anchorMin = Vector2.zero;

            orderCanvas.AddComponent<GraphicRaycaster>();

            _canvasDic[type] = orderCanvas;
        }
    }

    private GameObject RootCanvas
    {
        get
        {
            if (_rootCanvas == null)
            {
                _rootCanvas = GameObject.Find("Canvas");
            }
            return _rootCanvas;
        }
    }

    public GameObject GetCanvasByOrder(CanvasSortingOrderEnum orderEnum)
    {
        return _canvasDic[orderEnum];
    }


    public void AddPanel(GameObject panelPrefab)
    {
        if (panelPrefab == null)
        {
            Debug.LogError("UICanvasMgr panelPrefab is null");
            return ;
        }
        PanelControl panelControl = panelPrefab.GetComponent<PanelControl>();
        if (panelControl == null)
        {
            Debug.LogError("UICanvasMgr panelControl is null");
            return ;
        }
        UIHelper.Instance.AddChild(GetCanvasByOrder(panelControl.SortingOrder),panelPrefab);
    }
}
